//游戏配置
var gamecfg = {
	width: 800,
	height: 650,
	color: ['gray', 'red', 'green', 'purple', '#00a4e1']
};
//呈现canvas内容
var cxt = gamedis.getContext("2d");
var last_state;
var divp = [];
for (var i = 1; i <= 4; i++)
	divp[i] = {
		'team_name': document.getElementById('player_name' + i),
		'score': document.getElementById('player_score' + i)
	}
	//Image 资源加载器
function play_audio(src) {
	var audio = document.createElement('audio');
	audio.src = "res/" + src;
	audio.play();
}
var BGM = document.createElement('audio');
BGM.src = "res/4_SoundMgr_BackMusic_SoundMgr_BackMusic.mp3"
BGM.autoplay=false;
BGM.loop= "loop";

function ImageLoader() {
	var images = []; //图片资源(img标签数组)
	var count = 0; //要加载的图片数量
	var loaded = 0; //已加载图片数量
	var on_load_prograss = []; //当加载进度发生改变时要回调的函数列表
	//加载指定资源
	this.load = function(key, src, callback) {
		var img = new Image();
		img.src = src;
		count++;
		img.onload = function() {
			var can = document.createElement("canvas");
			can.height = img.height;
			can.width = img.width;
			var can_cxt = can.getContext('2d');
			can_cxt.drawImage(img, 0, 0);
			images[key] = can;
			loaded++;
			// console.log(img);
			for (var i in on_load_prograss)
				on_load_prograss[i](count, loaded, key, img);
			if (callback)
				callback();
		}
		images[key] = img;
	};
	//返回img对象
	this.getimg = function(key) {
		return images[key];
	};
	//将callback加入到on_load_prograss回调列表中
	this.onload = function(callback) {
		on_load_prograss.push(callback);
	}
};
var imgl = new ImageLoader();
//返回一个新的
function BufferCanvas() {
	var can = document.createElement('canvas');
	can.width = gamedis.width;
	can.height = gamedis.height;
	return can;
};

function DrawCell(context, x, y, r, img, rr) {
	var ratio = r / rr;
	var px = x - ratio * (img.width / 2);
	var py = y - ratio * (img.height / 2);
	context.drawImage(img, px, py, img.width * ratio, img.height * ratio);
}

function DrawTentacleNode(context, x, y, img, rot) {
	var ratio = 0.04;
	var width = img.width * ratio;
	var height = img.height * ratio;
	context.translate(x, y);
	context.rotate(rot);
	context.drawImage(img, -width / 2, -(height - 10) / 2, width, height);
	context.rotate(-rot);
	context.translate(-x, -y);
}

function DrawTentacle(context, x1, y1, x2, y2, img, tt) {
	var length = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
	var unit = {
		'x': (x1 - x2) / length,
		'y': (y1 - y2) / length
	};
	var vunit = {
		'x': -unit.y,
		'y': unit.x
	};
	//A*Sin(wr)
	var A = 4.0; //振幅
	var w = 0.1; //角速度
	var base_ang = -Math.PI / 2 + Math.atan2(unit.y, unit.x);
	for (var l = 0; l < length + 9.0; l += 10.0) {
		var sin = A * Math.sin(w * l + tt);
		var din = A * w * Math.cos(w * l + tt);
		var ang = base_ang + Math.atan(din);
		var p = {
			'x': x2 + l * unit.x + sin * vunit.x,
			'y': y2 + l * unit.y + sin * vunit.y
		};
		DrawTentacleNode(context, p.x, p.y, img, ang);
		context.fillRect(p.x, p.y, 1, 1);
	}
}

function DrawFrame(state) {
	var buffer_canvas = BufferCanvas();
	var buf = buffer_canvas.getContext('2d');
	var score = [0.0, 0.0, 0.0, 0.0, 0.0]; //各方积分
	buf.fillStyle = "#000";
	// buf.fillRect(0, 0, 800, 650);
	cxt.drawImage(imgl.getimg('background'), 0, 0);
	//绘制触须
	function cell_radius(cell) {
		return 18 + Math.sqrt(cell.hp + 1);
	};
	for (var i in state.tents) {
		var t = state.tents[i];
		// var side=state.cells[t.begin].side;
		var bcell = state.cells[t.begin];
		var ecell = state.cells[t.end];
		score[bcell.side] += (t.len1 + t.len2) * state.gconfig.t_density;
		var osegment = {
			'dx': ecell.x - bcell.x,
			'dy': ecell.y - bcell.y
		};
		osegment.len = Math.sqrt((osegment.dx * osegment.dx) + (osegment.dy * osegment.dy));
		var unit = {
			'x': osegment.dx / osegment.len,
			'y': osegment.dy / osegment.len
		};
		var bpoint = {
			'x': bcell.x + unit.x * cell_radius(bcell),
			'y': bcell.y + unit.y * cell_radius(bcell)
		}
		var epoint = {
			'x': ecell.x - unit.x * cell_radius(ecell),
			'y': ecell.y - unit.y * cell_radius(ecell)
		}
		var length = Math.sqrt((epoint.x - bpoint.x) * (epoint.x - bpoint.x) + (epoint.y - bpoint.y) * (epoint.y - bpoint.y));
		buf.strokeStyle = gamecfg.color[bcell.side];
		buf.lineWidth = t.energy * 25;
		// buf.beginPath();
		// buf.moveTo(bpoint.x, bpoint.y); //设置起点
		// buf.lineTo(bpoint.x + unit.x * t.len1 * length / osegment.len, bpoint.y + unit.y * t.len1 * length / osegment.len);
		// buf.closePath();
		// buf.stroke();
		DrawTentacle(buf, bpoint.x, bpoint.y, bpoint.x + unit.x * t.len1 * length / osegment.len, bpoint.y + unit.y * t.len1 * length / osegment.len, imgl.getimg('tentacle' + bcell.side), (state.tick_count) / 3.0);
		if (t.breaked) {
			// buf.beginPath();
			// buf.moveTo(epoint.x - unit.x * t.len2 * length / osegment.len, epoint.y - unit.y * t.len2 * length / osegment.len);
			// buf.lineTo(epoint.x, epoint.y);
			// buf.closePath();
			// buf.stroke();
			DrawTentacle(buf, epoint.x - unit.x * t.len2 * length / osegment.len, epoint.y - unit.y * t.len2 * length / osegment.len, epoint.x, epoint.y, imgl.getimg('tentacle' + bcell.side), (state.tick_count) / 3.0);
		}
	}
	//绘制生命
	for (var i in state.cells) {
		var c = state.cells[i];
		score[c.side] += c.hp;
		var img = imgl.getimg('lv' + c.level + c.side);
		DrawCell(buf, c.x, c.y, cell_radius(c), img, 171);
		if (last_state != null && last_state.cells != null && last_state.cells[i].side != c.side)
			play_audio("6_SoundMgr_CellOccupiedSnd_SoundMgr_CellOccupiedSnd.mp3")
			// buf.drawImage(img, c.x - img.width / 2, c.y - img.height / 2);
			//绘制生命值
		buf.font = "22px Arial"
		buf.fillStyle = "#FFF";
		buf.textAlign = 'center';
		buf.textBaseline = "middle";
		buf.fillText(Math.round(c.hp).toString(), c.x, c.y, 60);
	}
	cxt.drawImage(buffer_canvas, 0, 0);
	for (var i = 1; i <= 4; i++)
		divp[i]['score'].textContent = score[i].toFixed(2);
	for (var i = 0; i < 4; i++)
		divp[state.team_name[i].Key]['team_name'].textContent = state.team_name[i].Value;
	document.getElementById("tick_count").textContent = state.tick_count;
	// buffer_canvas=null;
	if (state.tick_count == 1000)
		BGM.pause();
}


cxt.fillRect(0, 0, 800, 650);

imgl.load('background', "./res/background.png", function() {
	cxt.drawImage(imgl.getimg('background'), 0, 0);
});
imgl.onload(function(count, loaded, key, img) {
	console.log('"' + loaded + '/' + count + '.' + key + '" loaded');
})
for (var side = 0; side <= 4; side++) {
	for (var level = 0; level <= 4; level++)
		imgl.load('lv' + level + side, 'res/lv' + level + side + '.png');
	imgl.load('tentacle' + side, 'res/tentacle' + side + '.png');
}
ws.onmessage = function(evt) {
	// inc.innerHTML += evt.data + '<br/>';
	// console.log(evt, evt.data);
	var state = JSON.parse(evt.data);
	BGM.play();
	DrawFrame(state);
	last_state = state;
};
